<template>
  <el-dialog :title="title" :visible="showDialog" @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请填写部门名称" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="请填写部门编码" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="form.managerId" placeholder="请选择负责人">
          <el-option v-for="item in form.managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="close()">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { getDepartmentList, getDepartmentPerson, addDepartmentList, getDepartmentDetail, updateDepartmentDetail } from '@/api/department'
export default {
  name: 'AddDepa',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      form: {
        name: '',
        code: '',
        managerId: '',
        introduce: '',
        pid: '',
        managerList: []
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 需求：新增部门
              // 1.查询所有的部门列表数据
              // 2.判断当前输入的部门名称是否在列表
              // 2.1如果在 ->不通过/校验失败 提示部门名称已经存在
              // 2.2如果不在 ->通过/校验成功
              let res = await getDepartmentList()
              // 需求：编辑部门不支持该规则
              // 来区分是编辑还是增加
              if (this.form.id) {
                // 排除自身，过滤
                res = res.filter(item => item.id !== this.form.id)
              }
              if (res.some(item => item.name === value)) {
                callback(new Error('部门名称已经存在'))
              } else {
                callback()
              }
            }
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 需求：新增部门
              // 1.查询所有的部门列表数据
              // 2.判断当前输入的部门名称是否在列表
              // 2.1如果在 ->不通过/校验失败 提示部门名称已经存在
              // 2.2如果不在 ->通过/校验成功
              let res = await getDepartmentList()
              // 需求：编辑部门不支持该规则
              // 来区分是编辑还是增加
              if (this.form.id) {
                // 排除自身，过滤
                res = res.filter(item => item.id !== this.form.id)
              }
              if (res.some(item => item.code === value)) {
                callback(new Error('部门编码已经存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 2, max: 300, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      let res = ''
      if (this.form.id) {
        res = `编辑部门`
      } else {
        res = `新增部门`
      }
      return res
    }
  },
  created() {
    this.getDepartmentPerson()
  },
  methods: {
    // 获取部门详情
    async getDepartmentDetail() {
      console.log('获取部门详情')
      const res = await getDepartmentDetail(this.currentNodeId)
      // console.log(res)
      this.form = res
    },
    async getDepartmentPerson() {
      const res = await getDepartmentPerson()
      console.log(res)
      this.form.managerList = res
    },
    close() {
      // 手动清除表单数据
      this.form = {
        name: '',
        code: '',
        managerId: '',
        introduce: '',
        pid: ''
      }
      // 1.关闭弹层
      this.$emit('update:showDialog', false)
      // 2.清空表单
      this.$refs.form.resetFields()
    },
    async onSubmit() {
      // 1.表单整体校验
      this.$refs.form.validate()
      if (this.form.id) {
        // 编辑
        await updateDepartmentDetail(this.form)
        this.$message.success('修改部门成功')
      } else {
        // 2.调用api新增部门
        await addDepartmentList({ ...this.form, pid: this.currentNodeId })
        // 3.提示用户
        this.$message.success('新增部门成功')
      }
      // 4.通知父组件更新 -> 更新部门数据
      this.$emit('updateDepartment')
      // 5.关闭弹层 + 清空表单
      this.close()
    }
  }
}
</script>
<style></style>
